import { expect } from '@jest/globals';
import fse from 'fs-extra';
import path from 'path';

import { addOhPackageDps, buildOneHapAndCheckFile, decompressHapAndReadEntries } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: [ModuleTemplateType.SharedLibrary]
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  // 1. 构建hap
  await buildOneHapAndCheckFile('entry')(project, taskConfig, record);

  // 2. 记录 ets/modules.abc 文件的大小
  // eslint-disable-next-line max-len
  const hapPath = path.resolve(project.getModule('entry').moduleRootPath(), 'build', 'default', 'outputs', 'default', 'entry-default-signed.hap');
  const modulesFileInfo = (await decompressHapAndReadEntries(hapPath)).find(item => item[0] === 'ets/modules.abc');
  expect(modulesFileInfo !== undefined).toBe(true);
  const oldModulesSize = modulesFileInfo![1];

  // 3. 给entry添加 SharedLibrary 依赖
  const entryPath = project.getModule('entry').moduleRootPath();
  await addOhPackageDps(entryPath, {
    'shareLibrary': '../shareLibrary'
  });

  // 4. 在entry中引入 add
  const indexPath = path.resolve(project.getModule('entry').moduleRootPath(),
    'src', 'main', 'ets', 'pages', 'Index.ets');
  let indexStr = (await fse.readFile(indexPath)).toString();
  // eslint-disable-next-line max-len
  indexStr = `import { add } from 'shareLibrary'\n\n${indexStr.replace('\'Hello World\'', '\'Hello World\' + add(1, 2)')}`;
  await fse.writeFile(indexPath, indexStr, 'utf-8');

  // 5. 重新构建hap
  await buildOneHapAndCheckFile('entry')(project, taskConfig, record);

  // 6. 重新记录 ets/modules.abc 文件的大小
  const modulesFileInfo1 = (await decompressHapAndReadEntries(hapPath)).find(item => item[0] === 'ets/modules.abc');
  expect(modulesFileInfo1 !== undefined).toBe(true);
  const newModulesSize = modulesFileInfo1![1];
  expect(Math.abs(newModulesSize - oldModulesSize) < 600).toBe(true);
};

TestCaseBuilder.builder()
  .caseName('OPEN_LAB_AIDE_ZOS_HOS_STAGE_Shared_Library_api10_002')
  .description('02、entry引用hsp模块')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L1).sign(SignType.Sign).build())
  .testFun(testFun)
  .load();
